<template>
  <div class="app-container correct">
    <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
      :model="formData" :rules="rules" size="medium" label-width="120px">
      <h2 style="text-align: center">不符合报告及纠正措施</h2>
      <h4 class="form-header h4">基础信息</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="管理体系内审" prop="innerCheckId">
            <el-select v-model="formData.innerCheckId" filterable @change="changeCheck" placeholder="请选择管理体系内审">
              <el-option v-for="dict in listcheck" :key="dict.innerCheckId" :label="dict.planYear + '年度内部工作计划明细'"
                :value="dict.innerCheckId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="责任部门" prop="deptId">
            <!-- <el-cascader :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false"
              ref="reference" @change="changeDept" placeholder="请选择责任部门" :style="{ width: '100%' }"
              v-model="formData.deptId" :options="deptOptions"></el-cascader> -->
            <el-select v-model="formData.deptId" multiple placeholder="请选择" @change="changeSelect">
              <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="责任部门负责人" prop="userId">
            <!-- <UserDialog :disabled="$route.query.isInfo || isInfo" v-model="formData.userId" @change="changeUser"></UserDialog> -->
            <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeUser" placeholder="请选择责任部门负责人"
              v-model="formData.userId"></UserDialogSelection>
          </el-form-item>
        </el-col>
      </el-row>
      <h4 class="form-header h4">
        明细
        <!-- <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button> -->
        <!-- <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button> -->
      </h4>
      <el-form ref="elForm2" :model="formData" :rules="rules">
        <el-table :data="formData.innerCorrectItem" :border="true" style="width: 100%">
          <el-table-column label="序号" type="index" align="center" />
          <el-table-column min-width="500" label="附件" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.file`" :rules="rules.file">
                <FileUpload :isDelete="!!(
                  extensionMap.fieldEdit &&
                  extensionMap.fieldEdit.split(',').includes('file')
                )
                  " v-model="scope.row.file"></FileUpload>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="条款" width="500" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.orderContent`" :rules="{
                required:
                  extensionMap.fieldEdit &&
                  extensionMap.fieldEdit.split(',').includes('orderContent'),
                message: '请选择条款',
                trigger: 'change',
              }">
                <el-input :disabled="true" v-model="scope.row.orderContent" placeholder="请选择条款"></el-input>
                <!-- <el-select :disabled="!(
                  extensionMap.fieldEdit &&
                  extensionMap.fieldEdit.split(',').includes('orderContent')
                )
                  " @change="changeOrder($event, scope.$index)" v-model="scope.row.innerCheckItemId" filterable
                  placeholder="请选择条款">
                  <el-option v-for="dict in listcheckContent" :key="dict.innerCheckItemId"
                    :label="dict.orderContent + dict.content" :value="dict.innerCheckItemId">
                    <div>
                      <el-tooltip popper-class="correct_item" effect="dark" :content="dict.content" placement="top-start">
                        <div style="
                            width: 200px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                          ">
                          {{ dict.orderContent }} {{ dict.content }}
                        </div>
                      </el-tooltip>
                    </div>
                  </el-option>
                </el-select> -->

              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="不符合类型" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.errorTypeValue`" :rules="{
                required:
                  extensionMap.fieldEdit &&
                  extensionMap.fieldEdit
                    .split(',')
                    .includes('errorTypeValue'),
                message: '请选择不符合类型',
                trigger: 'change',
              }">
                <el-select :disabled="!(
                  extensionMap.fieldEdit &&
                  extensionMap.fieldEdit
                    .split(',')
                    .includes('errorTypeValue')
                )
                  " v-model="scope.row.errorTypeValue" filterable placeholder="请选择不符合类型">
                  <el-option v-for="dict in dict.type.sys_error_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="不符合事实描述" min-width="200" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.errorDesc`" :rules="{
                required:
                  extensionMap.fieldEdit &&
                  extensionMap.fieldEdit.split(',').includes('errorDesc'),
                message: '请输入不符合事实描述',
                trigger: 'blur',
              }">
                <el-input :disabled="!(
                  extensionMap.fieldEdit &&
                  extensionMap.fieldEdit.split(',').includes('errorDesc')
                )
                  " v-model="scope.row.errorDesc" placeholder="请输入不符合事实描述"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <template v-if="formData.status">
            <el-table-column min-width="200" label="不合格原因分析" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.reason`" :rules="{
                  required:
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('reason'),
                  message: '请输入不合格原因分析',
                  trigger: 'blur',
                }">
                  <el-input :disabled="!(
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('reason')
                  )
                    " v-model="scope.row.reason" placeholder="请输入不合格原因分析"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column min-width="200" label="纠正措施" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.correct`" :rules="{
                  required:
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('correct'),
                  message: '请输入纠正措施',
                  trigger: 'blur',
                }">
                  <!-- !(
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('correct')
                  )
                     -->
                  <el-input :disabled="false" v-model="scope.row.correct" placeholder="请输入纠正措施"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column min-width="200" label="计划完成日期" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.finishDate`" :rules="{
                  required:
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('finishDate'),
                  message: '请选择日期',
                  trigger: 'change',
                }">
                  <!-- !(
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('finishDate')
                  )
                     -->
                  <el-date-picker :disabled="false" v-model="scope.row.finishDate" format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd" :style="{ width: '100%' }" placeholder="请选择日期" clearable></el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column min-width="200" label="完成情况" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="`innerCorrectItem.${scope.$index}.info`" :rules="{
                  required:
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('info'),
                  message: '请输入纠正措施完成情况',
                  trigger: 'blur',
                }">
                  <el-input :disabled="!(
                    extensionMap.fieldEdit &&
                    extensionMap.fieldEdit.split(',').includes('info')
                  )
                    " v-model="scope.row.info" placeholder="请输入完成情况"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

          </template>
          <el-table-column min-width="200" label="删除" align="center">
            <template slot-scope="scope">
              <el-button type="danger" plain size="mini" @click="handleDele(scope.$index)">删行</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm(1)">提交</el-button>
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm(0)">暂存</el-button>

          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="24" v-if="btnShow || extensionMap.fieldEdit">
        <el-form-item
          label-width="0"
          style="text-align: center; margin-top: 30px"
        >
          <el-button
            v-if="!($route.query.isInfo || isInfo) || extensionMap.fieldEdit"
            type="primary"
            :disabled="!extensionMap.fieldEdit"
            @click="submitForm"
            >提交</el-button
          >
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col> -->
    </el-form>
  </div>
</template>

<script>
import store from "@/store";

import { deptTreeSelect1 } from "@/api/system/user";
import { listcheckContentSetting } from "@/api/quality/checkContentSetting.js";
import {
  correctAdd,
  updategcorrect,
  correctInfo,
} from "@/api/quality/correct.js";
import { selectList } from "@/api/quality/checkItem.js";
import { selectList as selectListCheck } from "@/api/quality/check.js";

export default {
  components: {},
  dicts: ["sys_error_type"],
  props: {
    isInfo: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    btnShow: {
      type: Boolean,
      default: true,
    },
    extensionMap: {
      type: Object,
      default: {
        fieldEdit:
          "info,finishDate,correct,reason,errorDesc,errorTypeValue,orderContent",
      },
    },
  },
  data() {
    return {
      formData: {
        innerCheckId: undefined,
        deptId: [],
        deptName: [],
        innerCorrectItem: [
          // {
          //   orderContent: "",
          //   errorDesc: "",
          //   errorTypeValue: "",
          //   reason: "",
          //   correct: "",
          //   finishDate: "",
          //   result: "",
          //   info: "",
          //   file: "",
          //   innerCheckItemId:''
          // },
        ],
        deptId: undefined,
        userId: undefined,
      },
      rules: {
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "blur",
          },
        ],
        finishDate: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        userId: [
          {
            required: true,
            message: "请选择负责人",
            trigger: "blur",
          },
        ],
        innerCheckId: [
          {
            required: true,
            message: "请选择管理体系内审核查",
            trigger: "change",
          },
        ],
        errorDesc: [
          {
            required: true,
            message: "请输入不符合事实描述",
            trigger: "blur",
          },
        ],
        reason: [
          {
            required: true,
            message: "请输入不合格原因分析",
            trigger: "blur",
          },
        ],
        info: [
          {
            required: true,
            message: "请输入纠正措施完成情况",
            trigger: "blur",
          },
        ],
        file: [
          {
            required: false,
            message: "请上传附件",
            trigger: "change",
          },
        ],
        correct: [
          {
            required: true,
            message: "请输入纠正措施",
            trigger: "blur",
          },
        ],
        orderContent: [
          {
            required: true,
            message: "请选择条款号",
            trigger: "change",
          },
        ],
        errorTypeValue: [
          {
            required: true,
            message: "请选择不符合类型",
            trigger: "change",
          },
        ],
      },
      userList: [],
      deptId: [],
      deptName: [],
      deptOptions: [],
      planList: [],
      listcheckContent: [],
      listcheck: [],
      deptList: [],
      innerCheckItems: []
    };
  },
  computed: {},
  watch: {},
  created() {
    // this.getDeptTree();
    // setTimeout(()=>{

    // },500)
    if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo) {
      this.getinfo();
    }
    if (this.$route.query.innerCheckId) {
      this.formData.innerCheckId = Number(this.$route.query.innerCheckId);
      this.getList(this.formData.innerCheckId);
    }
    this.getCheck();
  },
  mounted() { },
  methods: {
    handleDele(e) {
      if (this.formData.innerCorrectItem.length == 1) return;
      this.formData.innerCorrectItem.splice(e, 1);
    },
    changeOrder(e, i) {
      console.log(e, i);
      let info = this.listcheckContent.find((_e) => _e.innerCheckItemId == e);
      this.formData.innerCorrectItem[i].content = info.content;
      this.formData.innerCorrectItem[i].orderContent = info.orderContent;
    },
    changeSelect(e) {
      console.log(e);


      console.log(this.deptName);
      // if(row){
      //   this.formData.deptId = row.deptId
      //   this.formData.deptName = row.deptName
      // }
    },
    changeDept(e) {
      console.log(e);
      // this.formData.userId = "";
      let arr = this.$refs.reference.getCheckedNodes()
      let list = []
      let label = []
      arr.forEach((item, index) => {
        list.push(item.value)
        label.push(item.label)
        console.log(item.value);
      })
      console.log(list);
      this.deptIdStringValue = list.toString()
      this.deptIdStringLabel = label.toString()
    },
    changeCheck(e) {
      console.log(e);
      let arr = this.listcheck.find((i) => i.innerCheckId === e)
      this.innerCheckItems = arr.innerCheckItems
      console.log(this.formData.innerCorrectItem, arr);
      // arr.innerCheckItems.forEach((lab, vle) => {
      //   console.log(this.formData.innerCorrectItem);
      //   this.formData.innerCorrectItem[vle].innerCheckItemId = lab.innerCheckItemId;
      // })
      // this.formData.innerCorrectItem = arr
      this.formData.innerCorrectItem.forEach((item, i) => {
        console.log(item);
        this.formData.innerCorrectItem[i].orderContent = "";
        this.formData.innerCorrectItem[i].innerCheckItemId = ''
      })
      console.log(this.listcheck.find((i) => i.innerCheckId === e));
      this.formData.planYear = this.listcheck.find(
        (i) => i.innerCheckId === e
      ).planYear;
      console.log(this.formData.planYear);
      this.getList(e);
      let ids = this.listcheck.find((i) => i.innerCheckId === e).deptIds
      console.log(ids);
      this.getDeptTree(ids)
      console.log(this.formData);
      // this.formData.innerCorrectItem.push(...arr)

    },
    getList(e) {
      selectList({
        innerCheckId: e,
      }).then((response) => {
        let arr = []
        response.data.forEach(item => {
          if (item.result == 'N') {
            arr.push(item)
            if (!this.$route.query.isEdit && !this.$route.query.isInfo && !this.isInfo) {
              this.formData.innerCorrectItem.push({
                orderContent: item.orderContent + item.content,
                errorDesc: "",
                errorTypeValue: "",
                reason: "",
                correct: "",
                finishDate: "",
                result: "",
                info: "",
                file: "",
              });
            } else {

            }

          }

        })
        this.listcheckContent = arr
        console.log(this.listcheckContent);
      });
    },
    getCheck() {
      selectListCheck().then((response) => {
        this.listcheck = response.data;
      });
    },
    changeUser(e) {
      console.log(e);
      let idList = []
      let nameList = []
      e.forEach((i) => {
        idList.push(i.userId)
        nameList.push(i.nickName)
      });
      console.log(idList, 'idList');
      this.formData.userId = idList.toString()
      this.formData.userName = nameList.toString()
      console.log(this.formData.userId);
    },
    handleAdd() {
      this.formData.innerCorrectItem.push({
        orderContent: "",
        errorDesc: "",
        errorTypeValue: "",
        reason: "",
        correct: "",
        finishDate: "",
        result: "",
        info: "",
        file: "",
      });
    },
    handleDele() {
      if (this.formData.innerCorrectItem.length == 1) return;
      this.formData.innerCorrectItem.pop();
    },

    /** 查询部门下拉树结构 */
    getDeptTree(e) {
      deptTreeSelect1({ deptIds: e }).then((response) => {
        this.deptOptions = response.data;

      });
    },

    getinfo() {
      return correctInfo(this.$route.query.id || this.id).then((response) => {
        this.getDeptTree(response.data.deptId)

        this.formData = response.data;
        this.formData.deptId = this.formData.deptId.split(',')
        // 将ID转number类型
        this.formData.deptId = this.formData.deptId.map(i => parseInt(i))
        // console.log(this.formData.deptId);
        // let list = []
        // // 多选部门回显取后端返回的ID
        // this.formData.deptId.map(i => {
        //   list.push(this.findParentLot(i))
        // })
        // this.formData.deptId = list
        console.log(this.formData.deptId);
        this.formData.userId = this.formData.userId.split(',')
        this.formData.userId = this.formData.userId.map((e) => parseInt(e));
        console.log(this.formData.userId);
        this.getList(this.formData.innerCheckId);
      });
      // 获取当前下的 审查明细
    },
    // 创建新数组 返回
    findParentLot(id) {
      const arr = []
      this.deployIdFun(this.deptOptions, id, arr)
      return arr.reverse()
    },
    // 逻辑代码 for循环 判断相同的id 取上级ID
    deployIdFun(options, id, newArr) {
      console.log(options);
      options.forEach((v) => {
        if (v.id === id) {
          newArr.push(id)
          console.log(newArr, 'newArr');
          if (!v.parentId || v.parentId !== '0') {
            this.deployIdFun(this.deptOptions, v.parentId, newArr)
          }
        } else {
          if (v.children && v.children.length) {
            this.deployIdFun(v.children, id, newArr)
          }
        }
      })
    },
    submitForm(e) {
      console.log(this.formData, this.deptList, this.deptId);
      const elForm2Promise = new Promise((resolve, reject) => {
        this.$refs["elForm2"].validate((valid) => {
          valid ? resolve() : reject();
        });
      });
      const elFormPromise = new Promise((resolve, reject) => {
        this.$refs["elForm"].validate((valid) => {
          valid ? resolve() : reject();
        });
      });
      return new Promise((resolve, reject) => {
        Promise.all([elFormPromise, elForm2Promise]).then(async () => {
          this.$refs["elForm"].validate((valid) => {
            if (valid) {
              let query = JSON.parse(JSON.stringify(this.formData));
              query.userId = query.userId.toString()
              query.deptId.forEach(item => {
                let row = this.deptOptions.find((l) => l.deptId == item).deptName;
                this.deptName.push(row)
              })
              console.log(this.deptName);
              query.deptId = query.deptId.toString()
              query.deptName = this.deptName.toString()
              query.innerCorrectItem.forEach((e, i) => {
                query.innerCorrectItem[i].errorTypeLabel =
                  this.dict.type.sys_error_type.find(
                    (e) => e.value === query.innerCorrectItem[i].errorTypeValue
                  ).label;
                console.log(e, this.innerCheckItems[i]);
                e.innerCheckItemId = this.innerCheckItems[i].innerCheckItemId
              });
              query.status = e == 0 ? 'draft' : 'audit'
              console.log(query);
              // query.innerCheckItems = this.innerCheckItems
              // return
              if (this.formData.innerCorrectId != undefined) {
                updategcorrect(query).then((response) => {
                  resolve();
                  if (!(e && e === "isFlow")) {
                    this.$modal.msgSuccess("修改成功");
                    this.resetForm();
                  }
                });
              } else {
                console.log(query);
                correctAdd(query).then((response) => {
                  resolve();
                  if (!(e && e === "isFlow")) {
                    this.$modal.msgSuccess("新增成功");
                    this.resetForm();
                  }
                });
              }
            } else {
              console.log("校验了");
              reject();
            }
          });
        });
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-top: 20px !important;
}
</style>
<style lang="scss">
.correct_item {
  margin: 4px;
  max-width: 80vw;
  width: 200px !important;
}
</style>
